#!/bin/bash

set -e

if [[ -n "${RASTER_VISION_DEBUG}" ]]; then
    set -x
fi

SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ] ; do SOURCE="$(readlink "$SOURCE")"; done
SCRIPTS_DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
SRC_DIR="$( cd -P "$( dirname "$SCRIPTS_DIR" )" && pwd )"

function usage() {
    echo -n \
"Usage: $(basename "$0")
Test that code is compliant with yapf (code formatter) and flake8.
"
}


if [ "${1:-}" = "--help" ]; then
    usage
else
    echo "Checking that code is consistent with flake8..."

    flake8 "$SRC_DIR" \
        --exclude ".git,build,docs,cookiecutter_template,*tfod_utils*,.history,data"

    # Exit code of 1 if yapf has a non-empty diff
    # (ie. scripts/format_code needs to be run)
    echo "Checking that code is consistent with yapf..."
    
    if !(yapf -dpr \
        -e "*build*" \
        -e "*.egg-info*" \
        -e "*cookiecutter_template*" \
        -e "*tfod_utils*" \
        -e "*.history*" \
        -e "**/*.ipynb" \
        "$SRC_DIR/rastervision_*/" "$SRC_DIR/tests/" "$SRC_DIR/integration_tests/" \
         > /dev/null); then
        echo "Code has not been formatted by yapf. Need to run ./scripts/format_code."
        exit 1
    fi
fi
